using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesAdminEEDLListing : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataObj CurPageDataObj = new DataObj();

    #region CurrentPageIndex
    protected int CurrentPageIndex
    {
        get
        {
            return (int)ViewState["CurrentPageIndex"];
        }

        set
        {
            ViewState["CurrentPageIndex"] = value;
        }
    }
    #endregion

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region ErrorMessage
    protected string ErrorMessage
    {
        get
        {
            return ViewState["ErrorMessage"].ToString();
        }

        set
        {
            ViewState["ErrorMessage"] = value;
        }
    }
    #endregion

    #region SuccessMessage
    protected string SuccessMessage
    {
        get
        {
            return ViewState["SuccessMessage"].ToString();
        }

        set
        {
            ViewState["SuccessMessage"] = value;
        }
    }
    #endregion

    #region SelectCompanyMessage
    protected string SelectCompanyMessage
    {
        get
        {
            return ViewState["SelectCompanyMessage"].ToString();
        }

        set
        {
            ViewState["SelectCompanyMessage"] = value;
        }
    }
    #endregion

    #region ArrayListHeader
    protected ArrayList ArrayListHeader
    {
        get
        {
            return (ArrayList)ViewState["ArrayListHeader"];
        }

        set
        {
            ViewState["ArrayListHeader"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
       
        this.SessionCheck();

        this.Table_MessageBox.Visible = false;

        if (!IsPostBack)
        {
            if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
            {
                if (!this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinancialManager)
                {
                    Button_Submit.Visible = false;
                }
            }

            this.CurrentPageIndex = 0; // set to 0

            this.SwitchLanguage();
            this.PageComponentSetup();

            this.LoadData();

            if (this.ResultTable != null)
            {
                DataView ResultView = new DataView(this.ResultTable);
                ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                this.BindData(ResultView);
            }
        }
    }
    #endregion

    #region DropDownList_ByEntity_SelectedIndexChanged
    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DropDownList_ByEntity.SelectedValue.Length > 0)
        {
            using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

                if (ResultList != null)
                {
                   

                    this.DropDownList_ByCompany.Items.Clear();
                    this.DropDownList_ByCompany.Items.Add(new ListItem("", ""));

                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByCompany.Items.Add(new ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesAdminEEDLListing.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        }

        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 1;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
        }
        #endregion
    }
    #endregion

    #region DropDownList_ByCompany_SelectedIndexChanged
    protected void DropDownList_ByCompany_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {
            this.LoadData();

            if (this.ResultTable != null)
            {
                

                DataView ResultView = new DataView(this.ResultTable);
                ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                this.BindData(ResultView);
            }
        }
    }
    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region DropDownList_SortOrder_SelectedIndexChanged
    protected void DropDownList_SortOrder_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region GridViewResult_PageIndexChanging
    protected void GridViewResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (this.ResultTable != null)
        {
            this.CurrentPageIndex = e.NewPageIndex;

            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region Button_Submit_Click
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        bool valid = true;

        if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {

            if (this.FileUpload_Template.PostedFile.ContentLength > 0)
            {
                StreamReader FileReader = new StreamReader(this.FileUpload_Template.PostedFile.InputStream, UTF8Encoding.UTF8);
                ArrayList DataList = new ArrayList();

                while (valid && FileReader.Peek() > -1)
                {
                    string FileLine = FileReader.ReadLine();
                    if (FileLine.Trim().Length > 0)
                    {
                        string[] DataArray = Regex.Split(FileLine, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                        //string[] DataArray = SwissArmy.StringSplit(FileLine, ",");

                        if (DataArray.Length == 8)
                        {
                            if(DataArray[2].Length > 0 && DataArray[3].Length > 0 && DataArray[4].Length > 0 && DataArray[5].Length > 0 && DataArray[6].Length > 0 && DataArray[0].Replace("\"","").ToString() != "Employee Name")
                                DataList.Add(DataArray);
                        }
                        //else
                        //{
                        //    valid = false;
                        //}
                    }
                }

                FileReader.Close();

                if (valid)
                {
                    using (GLClaimTypeManager CurManager = new GLClaimTypeManager(this.CurrentPrivateSession))
                    {
                        if (!CurManager.AddClaimTypeLimit(DataList, this.DropDownList_ByCompany.SelectedValue))
                        {
                            this.ShowErrorMessage(this.ErrorMessage);
                        }
                        else
                            this.ShowMessage(this.SuccessMessage);
                    }
                }
            }
        }
        else
        {
            this.ShowErrorMessage(this.SelectCompanyMessage);
        }
    }
    #endregion

    #region Button_Download_Click
    protected void Button_Download_Click(object sender, EventArgs e)
    {
        //bool valid = true;

        if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {
            GLClaimTypeManager GLManager = new GLClaimTypeManager(this.CurrentPrivateSession);
            DataTable dt = GLManager.GetClaimTypeLimitByCompany(this.DropDownList_ByCompany.SelectedItem.Value);

            if (dt != null)
            {
                Response.AddHeader("Content-Disposition", "attachment;filename=MasterList.csv");
                Response.ContentType = "text/csv";

                int iColCount = dt.Columns.Count;

                for (int i = 0; i < iColCount - 1; i++)
                {

                    Response.Write("\"" + dt.Columns[i] + "\"");
                    if (i < iColCount - 2)
                    {
                        Response.Write(",");

                    }
                }

                Response.Write(Environment.NewLine);
                // Now write all the rows.

                //foreach (DataRow dr in dt.Rows)
                for(int x=0; x<dt.Rows.Count; x++)
                {

                    for (int i = 0; i < iColCount - 1; i++)
                    {

                        if (!Convert.IsDBNull(dt.Rows[x][i]))
                        {
                            Response.Write("\"" + dt.Rows[x][i].ToString() + "\"");
                        }

                        if (i < iColCount - 2)
                        {
                            Response.Write(",");
                        }

                    }
                    Response.Write(Environment.NewLine);

                }
                Response.End();
            }
        }
        else
        {
            this.ShowErrorMessage("Please select a company");
        }
    }
    #endregion

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.ArrayListHeader.Count; i++)
            {
                cells[i].Text = this.ArrayListHeader[i].ToString();
            }
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin)
        {
            #region Power Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }

                    this.DropDownList_ByEntity.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID).Selected = true;
                    this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
                    this.DropDownList_ByCompany.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.InternalID).Selected = true;
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        if (Request.QueryString["entity"] != null && Request.QueryString["company"] != null)
        {
            this.DropDownList_ByEntity.SelectedItem.Selected = false;
            this.DropDownList_ByEntity.Items.FindByValue(Request.QueryString["entity"]).Selected = true;

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);

            this.DropDownList_ByCompany.Items.FindByValue(Request.QueryString["company"]).Selected = true;
        }
        else
        {

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
        }
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_FileUpload.Text = CurLanguageFactory.DisplayValue("FileUpload");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_UploadMessage.Text = CurLanguageFactory.DisplayValue("UploadMessage");
                this.Label_UploadMessage2.Text = CurLanguageFactory.DisplayValue("UploadMessage2");
                this.Button_Download.Text = CurLanguageFactory.DisplayValue("Download");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
                this.SuccessMessage = CurLanguageFactory.DisplayValue("SuccessMessage");
                this.ErrorMessage = CurLanguageFactory.DisplayValue("ErrorMessage");
                this.SelectCompanyMessage = CurLanguageFactory.DisplayValue("SelectCompanyMessage");

                this.ArrayListHeader = new ArrayList();
                this.ArrayListHeader.Add(CurLanguageFactory.DisplayValue("EmployeeIDWithLink"));
                this.ArrayListHeader.Add(CurLanguageFactory.DisplayValue("ADName"));
                this.ArrayListHeader.Add(CurLanguageFactory.DisplayValue("Name"));
                this.ArrayListHeader.Add(CurLanguageFactory.DisplayValue("Title"));
                this.ArrayListHeader.Add(CurLanguageFactory.DisplayValue("Email"));

                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ADName"), this.CurPageDataObj.ADName));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("EmployeeIDWithLink"), this.CurPageDataObj.EmployeeID));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Name"), this.CurPageDataObj.DisplayName));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Title"), this.CurPageDataObj.Title));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Email"), this.CurPageDataObj.Email));

                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesAdminEEDLListing.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    protected void LoadData()
    {
        // only when is selected from the drop down
        if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                SystemUsers ResultObj = CurUserManager.GetUsersByCompany(this.DropDownList_ByCompany.SelectedValue, true);

                if (ResultObj != null)
                {                    

                    this.ResultTable = new DataTable();
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.InternalID, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmployeeID, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmployeeIDWithLink, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ADName, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DisplayName, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.Title, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.Email, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmailWithLink, Type.GetType("System.String")));

                    for (int x = 0; x < ResultObj.Count; x++)
                    {
                        DataRow RowObj = ResultTable.NewRow();

                        RowObj[this.CurPageDataObj.InternalID] = ResultObj[x].InternalID;
                        RowObj[this.CurPageDataObj.EmployeeID] = ResultObj[x].EmployeeID;
                        RowObj[this.CurPageDataObj.EmployeeIDWithLink] = "<a class='GridViewLink' href='GonzalesAdminEEDLDetail.aspx?id=" + ResultObj[x].InternalID + "'>" + ResultObj[x].EmployeeID + "</a>";
                        RowObj[this.CurPageDataObj.ADName] = ResultObj[x].EmailID;
                        RowObj[this.CurPageDataObj.DisplayName] = ResultObj[x].DisplayName;
                        RowObj[this.CurPageDataObj.Title] = ResultObj[x].JobTitle;
                        RowObj[this.CurPageDataObj.Email] = ResultObj[x].Email;
                        RowObj[this.CurPageDataObj.EmailWithLink] = "<a href='mailto:" + ResultObj[x].Email + "'>" + ResultObj[x].Email + "</a>";

                        ResultTable.Rows.Add(RowObj);
                    }
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesAdminEEDLListing.LoadData] : Failed at CurUserManager.GetUsersByCompany() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }

            }
        }
    }

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #region Class: DataObj

    protected class DataObj
    {
        public readonly string InternalID = "InternalID";
        public readonly string EmployeeID = "EmployeeID";
        public readonly string EmployeeIDWithLink = "EmployeeIDWithLink";
        public readonly string ADName = "ADName";
        public readonly string DisplayName = "Name";
        public readonly string Title = "Title";
        public readonly string Email = "Email";
        public readonly string EmailWithLink = "EmailWithLink";
    }

    #endregion

}
